const CAS = 'http://localhost:8080';
const BACKEND = 'http://localhost:8082';
const PARAMS = new URLSearchParams(window.location.search);

document.addEventListener('DOMContentLoaded', (event) => {  
	fetchAndRenderStudent();
	fetchAndRenderSections();
});

function fetchAndRenderStudent() {
	// 生成URL
	const apiUrl = `${BACKEND}/student/${localStorage.getItem('account')}`;
	// 向URL发送请求
	fetch(apiUrl, {
		credentials: 'include'
		})
	    .then(response => {  
	        if (!response.ok) {  
	            throw new Error('Failed to fetch');  
	        }  
			// 依据json格式解析HTTP响应体
	        return response.json();  
	    })  
	    .then(data => {  
			// 填充数据到HTML文档上
			const studentInfoContainer = document.getElementById('student-name');
			studentInfoContainer.innerHTML = data.name;
	    })  
	    .catch(error => {  
	        console.error('Error fetching:', error);  
	    });  
}

function fetchAndRenderSections() {
	const apiUrl = `${BACKEND}/student/${localStorage.getItem('account')}/section`;
	const coursesList = document.getElementById('class-list');  	  
	fetch(apiUrl, {
		credentials: 'include'
	})  
	    .then(response => {  
	        if (!response.ok) {  
	            throw new Error('Failed to fetch classes');  
	        }  
	        return response.json();  
	    })  
	    .then(data => {  
			data.forEach(course => {
			    const listItem = document.createElement('li');  
				const semester = document.createElement('h3');
				const courseDOM = document.createElement('h3');
				const total = document.createElement('p');
				semester.textContent = course.section.semester;
				courseDOM.textContent = course.course.name;
				total.textContent = course.score.total;
			    listItem.appendChild(semester);
				listItem.appendChild(courseDOM);
				listItem.appendChild(total);
			    coursesList.appendChild(listItem);  
			});
	    })  
	    .catch(error => {  
	        console.error('Error fetching classes:', error);  
	    });  
}

const logoutBtn = document.getElementById('logoutBtn');
logoutBtn.addEventListener('click', ()=>{
	window.location.href = `${CAS}/logout-page`;
	localStorage.setItem('account', null);
	localStorage.setItem('token', null);
});